package com.dq.controller.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;
import java.util.Random;
import java.util.UUID;

/**
 * Created by EDZ on 2018/3/17.
 *
 * @author zhangzeli
 */
public class Md5Object {

    private static final Logger LOGGER = LoggerFactory.getLogger(Md5Object.class);
    private final static Base64.Decoder DECODER = Base64.getDecoder();
    private final static Base64.Encoder ENCODER = Base64.getEncoder();

    /**
     * 全局数组
     **/
    private final static String[] STRDIGITS = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private final static String BASE = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public Md5Object() {
    }

    /**
     * 返回形式为数字跟字符串
     **/
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return STRDIGITS[iD1] + STRDIGITS[iD2];
    }

    /**
     * 转换字节数组为16进制字串
     **/
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String encrypt(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(strObj.getBytes("UTF-8")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

    /**
     * 时间戳:ETag
     *
     * @return String
     */
    public static String getNonce() {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        String timeTemp = Instant.now().toString();
        sb.append(timeTemp).append("ETag");
        for (int i = 0; i < BASE.length()/2; i++) {
            int number = random.nextInt(BASE.length());
            sb.append(BASE.charAt(number));
        }
        String nonce;
        try {
            nonce = ENCODER.encodeToString(sb.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("", e);
            nonce = sb.toString();
        }
        return nonce;
    }

    public static String uuid(){
        UUID uuid  =  UUID.randomUUID();
        return uuid.toString().replaceAll("\\-", "");
    }
}
